package com.shd.edanpei.presenter;

import android.app.Dialog;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.shd.edanpei.R;
import com.shd.edanpei.ui.activity.MeProductsActivity;
import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.dialog.DialogUtil;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ExceptionHandler;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.bean.OrderListModel;
import com.shd.edanpei.bean.TakeOrderBean;
import com.shd.edanpei.bean.PagingModel;
import com.shd.edanpei.presenter.contract.ShareOrderContract;
import com.shd.edanpei.enums.OrderTypeEnum;
import com.shd.edanpei.util.LayoutUtils;
import com.shd.edanpei.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/9/25.
 * yang-wen-wen
 */

public class ShareOrderPresenter extends BasePresenterImpl<ShareOrderContract.ShareOrderIView>
        implements ShareOrderContract.ShareOrderIPresenter {

    private int currentPage;
    private int totalPage;

    public ShareOrderPresenter(ShareOrderContract.ShareOrderIView mView) {
        super(mView);
    }

    @Override
    public void refresh() {
        currentPage = 1;
        ApiCreator.getApi().robOrderList(currentPage)
                .compose(RxTransformer.<PagingModel<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PagingModel<OrderListModel>>() {
                    @Override
                    protected void onSuccess(PagingModel<OrderListModel> data) {

//
                        if (data != null && data.getList().size() > 0) {
                            totalPage = data.getTotalPage();
                            List<OrderListModel> list = new ArrayList<>();
                            for (int i = 0; i < data.getList().size(); i++) {
                                if (data.getList().get(i).getOrderType() != OrderTypeEnum.normal.getKey()) {
                                    list.add(data.getList().get(i));
                                }
                            }
                            if (list.size() != 0) {
                                mBaseIView.getAdapter().setNewData(list);
                            } else {
                                mBaseIView.getAdapter().setEmptyView(LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.pic_null_bg, "暂无更多订单，请耐心等待"));
                            }
                            if (currentPage >= totalPage) {
                                mBaseIView.getAdapter().loadMoreEnd();
                            } else {
                                mBaseIView.getAdapter().loadMoreComplete();
                            }
                            currentPage++;
                        } else {
                            mBaseIView.getAdapter().setNewData(null);
                            View nullView=LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.no_list_data, "暂无相关订单");
                            mBaseIView.getAdapter().setEmptyView(nullView);
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        if (throwable.getCode() == ExceptionHandler.UNUPLOAD_PRODUCT) {
                            //未上架产品
                            mBaseIView.getAdapter().setEmptyView(getUnUnploadLayout(throwable.getMessage()));
                        } else {
                            mBaseIView.getAdapter().setEmptyView(LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.pic_null_bg, "暂无相关订单"));
                        }
                    }

                    @Override
                    public void onFinish() {
                        if (mBaseIView != null) {
                            mBaseIView.getRefreshLayout().setRefreshing(false);
                        }
                    }
                });


    }

    @Override
    public void loadMore() {
        ApiCreator.getApi().robOrderList(currentPage)
                .compose(RxTransformer.<PagingModel<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PagingModel<OrderListModel>>() {
                    @Override
                    protected void onSuccess(PagingModel<OrderListModel> data) {
                        if (data != null && data.getList().size() > 0) {

                            List<OrderListModel> list = new ArrayList<>();
                            for (int i = 0; i < data.getList().size(); i++) {
                                if (data.getList().get(i).getOrderType() != OrderTypeEnum.normal.getKey()) {
                                    list.add(data.getList().get(i));
                                }
                            }
                            mBaseIView.getAdapter().addData(list);
                            if (currentPage >= totalPage) {
                                mBaseIView.getAdapter().loadMoreEnd();
                            } else {
                                mBaseIView.getAdapter().loadMoreComplete();
                            }
                            currentPage++;
                        } else {
                            mBaseIView.getAdapter().loadMoreEnd();
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getAdapter().loadMoreEnd();
                    }
                });
    }

    @Override
    public void allRefresh() {
        currentPage = 1;
        ApiCreator.getApi().findAllOrdres(currentPage)
                .compose(RxTransformer.<PagingModel<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PagingModel<OrderListModel>>() {
                    @Override
                    protected void onSuccess(PagingModel<OrderListModel> data) {
                        if (data != null && data.getList().size() > 0) {
                            totalPage = data.getTotalPage();
                            List<OrderListModel> list = new ArrayList<>();
                            for (int i = 0; i < data.getList().size(); i++) {
                                if (data.getList().get(i).getOrderType() != OrderTypeEnum.normal.getKey()) {
                                    list.add(data.getList().get(i));
                                }
                            }
                            if (list.size() != 0) {
                                mBaseIView.getAdapter().setNewData(list);
                            } else {
                                mBaseIView.getAdapter().setEmptyView(LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.pic_null_bg, "暂无更多订单，请耐心等待"));
                            }
                            if (currentPage >= totalPage) {
                                mBaseIView.getAdapter().loadMoreEnd();
                            } else {
                                mBaseIView.getAdapter().loadMoreComplete();
                            }
                            currentPage++;
                        } else {
                            mBaseIView.getAdapter().setNewData(null);
                            mBaseIView.getAdapter().setEmptyView(LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.pic_null_bg, "暂无更多订单，请耐心等待"));
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        if (throwable.getCode() == ExceptionHandler.UNUPLOAD_PRODUCT) {
                            //未上架产品
                            mBaseIView.getAdapter().setEmptyView(getUnUnploadLayout(throwable.getMessage()));
                        } else {
                            mBaseIView.getAdapter().setEmptyView(LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.pic_null_bg, "暂无更多订单，请耐心等待"));
                        }
                    }

                    @Override
                    public void onFinish() {
                        if (mBaseIView != null) {
                            mBaseIView.getRefreshLayout().setRefreshing(false);
                        }
                    }
                });
    }

    @Override
    public void allLoadMore() {
        ApiCreator.getApi().findAllOrdres(currentPage)
                .compose(RxTransformer.<PagingModel<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PagingModel<OrderListModel>>() {
                    @Override
                    protected void onSuccess(PagingModel<OrderListModel> data) {
                        if (data != null && data.getList().size() > 0) {
                            List<OrderListModel> list = new ArrayList<>();
                            for (int i = 0; i < data.getList().size(); i++) {
                                if (data.getList().get(i).getOrderType() != OrderTypeEnum.normal.getKey()) {
                                    list.add(data.getList().get(i));
                                }
                            }
                            mBaseIView.getAdapter().addData(list);
                            if (currentPage >= totalPage) {
                                mBaseIView.getAdapter().loadMoreEnd();
                            } else {
                                mBaseIView.getAdapter().loadMoreComplete();
                            }
                            currentPage++;
                        } else {
                            mBaseIView.getAdapter().loadMoreEnd();
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getAdapter().loadMoreEnd();
                    }
                });
    }


    @Override
    public void take(final int orderID, final int index) {

        View view = View.inflate(mBaseIView.getContext(), R.layout.dialog_take_code, null);
        final EditText etCode = view.findViewById(R.id.et_code);
        View sure = view.findViewById(R.id.sure);

        final Dialog takeDialog = new Dialog(mBaseIView.getContext(), R.style.inputDialog);
        takeDialog.setContentView(view);
        takeDialog.setCanceledOnTouchOutside(true);
        takeDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                etCode.setText("");
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = etCode.getText().toString();
                if (!TextUtils.isEmpty(code)) {
                    takeDialog.dismiss();
                    takeOrder(orderID, index, code);
                }
            }
        });

        takeDialog.show();

    }

    private void takeOrder(int orderID, final int index, String code) {
        mBaseIView.showLoading("接单中...");
        ApiCreator.getApi().takeOrder(orderID, code)
                .compose(RxTransformer.<TakeOrderBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<TakeOrderBean>() {
                    @Override
                    protected void onSuccess(TakeOrderBean data) {
                        if (data.getCode().equals("1")) {
                            mBaseIView.getAdapter().remove(index);
                            //抢单列表是否还有数据
                            if (mBaseIView.getAdapter().getData().size() == 0) {
                                refresh();
                            }
                            DialogUtil.showTakeSuccessDialog(mBaseIView.getContext(), new DialogUtil.TwoListener() {

                                @Override
                                public void cancel() {

                                }

                                @Override
                                public void sure() {
                                    RxBus.get().send(RxBusCode.CHECK_SHARE_ORDER);
                                }
                            });
                        } else if (data.getCode().equals("3")) {
                            ToastUtil.showToast(data.getMsg());
                        }
                    }

                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
    }


    private View getUnUnploadLayout(String content) {
        View view = LayoutInflater.from(mBaseIView.getContext()).inflate(R.layout.null_order_layout, null);
        TextView tvContent = view.findViewById(R.id.tv_null_content);
        TextView tv = view.findViewById(R.id.tv_order_go);
        tvContent.setText("请前去新增产品，立即为您匹配订单");
        tv.setText("去新增");
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBaseIView.startActivity(MeProductsActivity.class);
            }
        });
        return view;
    }
}
